package com.yf.internedstring;

import org.junit.Test;

/**
 * 字面量形式声明的字符串，存储在字符串常量池中
 */
public class StringTest {

    @Test
    public void test1() {
        String s1 = "hello";
        String s2 = "hello";

        System.out.println(s1 == s2); // true
        /*
        在字符串常量池（Interned String）中不允许出现相同的字符串
         */
    }

    @Test
    public void test11() {
        String s1 = new String("hello");
        String s2 = new String("hello");

        System.out.println(s1 == s2); // true
        /*
        在字符串常量池（Interned String）中不允许出现相同的字符串
         */
    }

    @Test
    public void test2() {
        String s1 = "abc";
        String s2 = "abc";

        s2 += "def";
        System.out.println(s1 == s2); // false
        System.out.println(s1); // abc
        System.out.println(s2); // abcdef
        /*
        字符串常量不可变的，一旦修改就会重新创建
         */
    }

    @Test
    public void test3() {
        String s1 = "abc";
        String s2 = s1.replace('a', 'm');
        System.out.println(s1);
        System.out.println(s2);
    }


    @Test
    public void test5() {
        String s = new String("3");
        s.intern();
        String s2 = "3";
        System.out.println(s == s2); // jdk6,jdk7,jdk8:false

        String s3 = new String("3") + new String("3");
        s3.intern();
        String s4 = "33";
        System.out.println(s3 == s4); // jdk6:false, jdk7:true, jdk8:true
    }

    @Test
    public void test6() {
        String s3 = new String("3") + new String("3");
        s3.intern();
        String s4 = "33";
        System.out.println(s3 == s4); // jdk6:false, jdk7:true, jdk8:true
    }

}
